import { Form,Icon,Input, Select,Button, Radio,Checkbox, Divider } from "antd";
import React from "react";
import styles from "../../index.less"
import { fetchApiListById } from "@/services/basiccapacity";
import { formFieldList } from "@/services/formInteraction";
import ApiTableConfig from "./apiTableConfig";
import Editor from '@/utils/Editor';
import CardConfig from "../cardConfig";

class ApiNode extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      buttonInfo:{
        confirmButtonSelected:1,
        confirmButtonName:"确定",
        cancelButtonSelected:0,
        cancelButtonName:"取消",
        resetButtonSelected:0,
        resetButtonName:"重置"
      },
      editConfirm:false,
      editCancel:false,
      editReset:false,
      apiList:[],
      fieldsList:[],
      searchInfo:{
        requestList:[],
        responseList:[]
      },
      submitInfo:{
        requestList:[],
        responseList:[]
      },
      searchFieldReqParam:[
        {
          formFieldId:"",
          apiFieldId:""
        }
      ],
      searchFieldResParam:[
        {
          formFieldId:"",
          apiFieldId:""
        }
      ],
      resultFieldReqParam:[
        {
          fieldType:"",
          sendFieldId:"",
          formFieldId:"",
          apiFieldId:""
        }
      ],
      resultFieldResParam:[
        {
          formFieldId:"",
          apiFieldId:""
        }
      ],
      resultContent:'',
      configurationCardStyle:{},
      optionDoubleConfirmationContent:''
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initForm = data => {
    const { form:{setFieldsValue} } = this.props;
    
    this.getFieldsList()
    setFieldsValue({label:data.label})
    if(data.data){
      const info = data.data.api      
      setFieldsValue({
        type:info.type,
        buttonTrigger:info.buttonTrigger,
        searchApiId:info.searchApiId,
        resultShowType:info.resultShowType == 1
      })

      //查询展示API
      if(info.type == 1){
        setFieldsValue({displayCardSelectedType:info.displayCardSelectedType})
        if(info.displayCardSelectedType == 1){
          //展示卡可被选择
          setFieldsValue({
            optionDoubleConfirmation:info.optionDoubleConfirmation,
            dataSubmitType:info.dataSubmitType
          })
        }
        
        try{
          this.setState({
            configurationCardStyle:info.configurationCardStyle ? JSON.parse(info.configurationCardStyle) : {}
          })
        }catch(e){}

        //数据提交返回-是
        if(info.dataSubmitType == 1){
          setFieldsValue({submitApiId:info.submitApiId})
        }
        
      }

      this.setState({
        buttonInfo:{
          confirmButtonSelected:info.confirmButtonSelected,
          confirmButtonName:info.confirmButtonName,
          cancelButtonSelected:info.cancelButtonSelected,
          cancelButtonName:info.cancelButtonName,
          resetButtonSelected:info.resetButtonSelected,
          resetButtonName:info.resetButtonName
        },
        resultFieldReqParam:info.resultFieldReqParam ? info.resultFieldReqParam : [{fieldType:"",sendFieldId:"",formFieldId:"",apiFieldId:""}],
        resultFieldResParam:info.resultFieldResParam ? info.resultFieldResParam : [{formFieldId:"",apiFieldId:""}],
        searchFieldReqParam:info.searchFieldReqParam ? info.searchFieldReqParam : [{formFieldId:"",apiFieldId:""}],
        searchFieldResParam:info.searchFieldResParam ? info.searchFieldResParam : [{formFieldId:"",apiFieldId:""}],
        resultContent:info.resultContent,
        optionDoubleConfirmationContent:info.optionDoubleConfirmationContent
      })
      if(info.type == 1 && info.dataSubmitType == 1){
        this.getApiList('init',info.searchApiId,'searchInfo',info.submitApiId,'submitInfo')
      }else{
        this.getApiList('init',info.searchApiId,'searchInfo')
      }
    }else{
      this.getApiList()
    }
  }

  checkSave = () => {
    const { buttonInfo,searchFieldReqParam,searchFieldResParam,resultFieldReqParam,resultFieldResParam,configurationCardStyle} = this.state;
    this.props.form.validateFields((error,values) => {
      values.resultShowType = values.resultShowType ? 1 : 0
      if(!error){
        let obj = {
          label:values.label,
          data:{
            api:{
              ...values,
              ...buttonInfo,
              resultContent:this.refs['answerContent'] ? this.refs['answerContent'].getUeditorContent() : '',
              searchFieldReqParam,searchFieldResParam,resultFieldReqParam,resultFieldResParam,
              optionDoubleConfirmationContent:this.refs['optionDoubleConfirmationContent'] ? this.refs['optionDoubleConfirmationContent'].getUeditorContent() : '',
            }
          }
        }
        try{
          if(values.type == 1 && this.CardConfig){
            obj.data.api.configurationCardStyle = JSON.stringify(configurationCardStyle)
          }
        }catch(e){}
        
        this.props.doSave(obj)
      }
    })
  }

  changeType = value => {

  }

  changeName = (e,type) => {
    const { buttonInfo } = this.state;
    buttonInfo[type] = e.target.value;
    this.setState({
      buttonInfo
    })
  }

  doNameEdit = (nameType,editType) => {
    const { buttonInfo } = this.state;
    if(buttonInfo[nameType].length == 0){
      message.error("请输入按钮名字")
      return false
    }
    let obj = {}
    obj[editType] = false;
    this.setState(obj)
  }

  changeCancelSelect = e => {
    const { buttonInfo } = this.state;
    buttonInfo.cancelButtonSelected = e.target.checked ? 1 : 0
    this.setState({
      buttonInfo
    })
  }

  changeResetButtonSelected = e => {
    const { buttonInfo } = this.state;
    buttonInfo.resetButtonSelected = e.target.checked ? 1 : 0
    this.setState({
      buttonInfo
    })
  }

  getApiList = async (flag,searchApiId,paramsType,submitApiId,paramsType2) => {
    const res = await fetchApiListById({current:1,size:9999999999999999,type:1})
    this.setState({
      apiList:res.records
    },() => {
      if(flag == 'init'){
        this.changeApiId(searchApiId,paramsType)
        if(submitApiId){
          this.changeApiId(submitApiId,paramsType2)
        }
      }
    })
  }

  getFieldsList = async () => {
    const { formId } = this.props;
    const res = await formFieldList({formId})
    this.setState({
      fieldsList:res
    })
  }

  changeApiId = (value,type) => {
    const { apiList } = this.state;
    let requestList = []
    let responseList = []
    for(const item of apiList){
      if(item.id == value){
        requestList = item.fieldList ? item.fieldList.filter(f => f.type == 1 ) : []
        responseList = item.fieldList ? item.fieldList.filter(f => f.type == 2 ) : []
      }
    }
    this.setState({
      [type]:{
        requestList,
        responseList
      }
    })
  }

  /**
   * 
   * @param {下拉框修改的值} value 
   * @param {修改的索引} index 
   * @param {修改的数据} listType 
   * @param {修改的数据中的属性} valueType 
   */
  changeOption = (value,index,listType,valueType) => {
    const list = JSON.parse(JSON.stringify(this.state[listType]))
    list[index][valueType] = value;
    if(valueType == 'fieldType'){
      list[index].apiId = ''
      list[index].sendFieldId = ''
    }
    if(valueType == 'apiId'){
      list[index].sendFieldId = ''
    }
    this.setState({
      [listType]:JSON.parse(JSON.stringify(list))
    })
  }

  addContent = listType => {
    const list = JSON.parse(JSON.stringify(this.state[listType]))
    list.push({
      formFieldId:"",
      apiFieldId:""
    })
    this.setState({
      [listType]:JSON.parse(JSON.stringify(list))
    })
  }

  removeContent = (index,listType) => {
    const list = JSON.parse(JSON.stringify(this.state[listType]))
    let newList = []
    for(const i in list){
      if(i != index){
        newList.push(list[i])
      }
    }

    this.setState({
      [listType]:JSON.parse(JSON.stringify(newList))
    })
  }

  changeFieldType = (value,index) => {
    let list = JSON.parse(JSON.stringify(this.state.resultFieldReqParam))
    list[index].fieldType = value;
    this.setState({
      resultFieldReqParam:JSON.parse(JSON.stringify(list))
    })
  }

  openCardConfig = () => {
    const { configurationCardStyle } = this.state;
    this.CardConfig.getDetail(configurationCardStyle)
  }

  setCardConfigData = data => {
    this.setState({
      configurationCardStyle:data
    })
  }

  render(){
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    const { 
      buttonInfo,
      editCancel,
      editConfirm,
      editReset,
      apiList,
      fieldsList,
      searchInfo,
      submitInfo,
      searchFieldReqParam,
      searchFieldResParam,
      resultFieldReqParam,
      resultFieldResParam,
      resultContent,
      optionDoubleConfirmationContent
    } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    return(
      <Form {...formItemLayout}>
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />基本信息</div>
        <Form.Item label="节点名称">
          {
            getFieldDecorator("label",{rules:[{required:true,message:"请输入"}]})(
              <Input className={styles.inputItem} />
            )
          }
        </Form.Item>
        <Form.Item label="操作类型">
          {
            getFieldDecorator("type",{initialValue:0,rules:[{required:true,message:"请输入"}]})(
              <Radio.Group>
                <Radio value={0}>直接调用API</Radio>
                <Radio value={1}>查询展示API</Radio>
              </Radio.Group>
            )
          }
        </Form.Item>
        <Divider />
        <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />查询区</div>
        {
        //   <Form.Item label="按钮触发查询">
        //   {
        //     getFieldDecorator("buttonTrigger",{initialValue:0,rules:[{required:true,message:"请输入"}]})(
        //       <Radio.Group>
        //         <Radio value={1}>是</Radio>
        //         <Radio value={0}>否</Radio>
        //       </Radio.Group>
        //     )
        //   }
        // </Form.Item>
        }
        {
        //   <Form.Item label="按钮选择">
        //   <div style={{display:"flex"}}>
        //     <div>
        //       <Checkbox checked={buttonInfo.confirmButtonSelected == 1 } disabled />
        //       {
        //         editConfirm ? (
        //           <span style={{display:"inline-block"}}>
        //             <Input value={buttonInfo.confirmButtonName} onChange={(e) => this.changeName(e,'confirmButtonName')} style={{width:200,marginLeft:10}} />
        //             <Icon type="check" style={{marginLeft:5,cursor:"pointer"}} onClick={() => this.doNameEdit('confirmButtonName','editConfirm')} />
        //           </span>
        //         ) : (
        //           <span style={{display:"inline-block"}}>
        //             <label style={{marginLeft:5}}>{buttonInfo.confirmButtonName}</label>
        //             <Icon type="form" style={{marginLeft:5,cursor:"pointer"}} onClick={() => this.setState({editConfirm :true})} />
        //           </span>
        //         )
        //       }
              
        //     </div>
        //     <div style={{margin:"0 15px"}}>
        //       <Checkbox checked={buttonInfo.cancelButtonSelected == 1 } onChange={this.changeCancelSelect} />
        //       {
        //         editCancel ? (
        //           <span style={{display:"inline-block"}}>
        //             <Input value={buttonInfo.cancelButtonName} onChange={(e) => this.changeName(e,'cancelButtonName')} style={{width:200,marginLeft:10}} />
        //             <Icon type="check" style={{marginLeft:5,cursor:"pointer"}} onClick={() => this.doNameEdit('cancelButtonName','editCancel')} />
        //           </span>
        //         ) : (
        //           <span style={{display:"inline-block"}}>
        //             <label style={{marginLeft:5}}>{buttonInfo.cancelButtonName}</label>
        //             <Icon type="form" style={{marginLeft:5,cursor:"pointer"}} onClick={() => this.setState({editCancel :true})} />
        //           </span>
        //         )
        //       }
              
        //     </div>
        //     <div>
        //       <Checkbox checked={buttonInfo.resetButtonSelected == 1 } onChange={this.changeResetButtonSelected} />
        //       {
        //         editReset ? (
        //           <span style={{display:"inline-block"}}>
        //             <Input value={buttonInfo.resetButtonName} onChange={(e) => this.changeName(e,'resetButtonName')} style={{width:200,marginLeft:10}} />
        //             <Icon type="check" style={{marginLeft:10,cursor:"pointer"}} onClick={() => this.doNameEdit('resetButtonName','editReset')} />
        //           </span>
        //         ) : (
        //           <span style={{display:"inline-block"}}>
        //             <label style={{marginLeft:10}}>{buttonInfo.resetButtonName}</label>
        //             <Icon type="form" style={{marginLeft:10,cursor:"pointer"}} onClick={() => this.setState({editReset :true})} />
        //           </span>
        //         )
        //       }
              
        //     </div>
        //   </div>
        // </Form.Item>
        }
        
        <Form.Item label="接口选择">
          {
            getFieldDecorator("searchApiId",{rules:[{required:true,message:"请选择"}]})(
              <Select onChange={(value) => this.changeApiId(value,"searchInfo")}>
                {
                  apiList.map(item => {
                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                  })
                }
              </Select>
            )
          }
        </Form.Item>
        <Form.Item label="请求参数赋值">
          <ApiTableConfig 
            title1="表单字段" 
            title2="接口字段" 
            options1={fieldsList} 
            options2={searchInfo.requestList} 
            list={searchFieldReqParam}
            valueType1={'formFieldId'}
            valueType2={'apiFieldId'}
            changeOption={this.changeOption}
            listType={'searchFieldReqParam'}
            addContent={this.addContent}
            removeContent={this.removeContent}
          />
        </Form.Item>
        <Form.Item label="返回参数赋值">
          <ApiTableConfig 
            title1="接口字段" 
            title2="表单字段" 
            options1={searchInfo.responseList} 
            options2={fieldsList} 
            list={searchFieldResParam}
            valueType2={'formFieldId'}
            valueType1={'apiFieldId'}
            changeOption={this.changeOption}
            listType={'searchFieldResParam'}
            addContent={this.addContent}
            removeContent={this.removeContent}
          />
          
        </Form.Item>

        {
          getFieldValue("type") == 1 ? (
            <div>
              <Form.Item label="内容展示配置">
                <Button type="primary" icon="setting" onClick={this.openCardConfig}>配置卡片样式</Button>
              </Form.Item>
              <Form.Item label="展示卡可被选">
                {
                  getFieldDecorator("displayCardSelectedType",{initialValue:0,rules:[{required:true,message:"请输入"}]})(
                    <Radio.Group>
                      <Radio value={1}>是</Radio>
                      <Radio value={0}>否</Radio>
                    </Radio.Group>
                  )
                }
              </Form.Item>
              {
                getFieldValue("displayCardSelectedType") == 1 ? (
                  <Form.Item label="选项二次确认">
                    {
                      getFieldDecorator("optionDoubleConfirmation",{initialValue:0,rules:[{required:true,message:"请输入"}]})(
                        <Radio.Group>
                          <Radio value={1}>是</Radio>
                          <Radio value={0}>否</Radio>
                        </Radio.Group>
                      )
                    }
                  </Form.Item>
                ) : ''
              }
              
              

              {
                //二次确认内容配置
                getFieldValue("optionDoubleConfirmation") == 1 && getFieldValue("displayCardSelectedType") == 1 ? (
                  <Form.Item label="二次确认内容配置">
                    <div style={{lineHeight:'24px'}}><Editor content={optionDoubleConfirmationContent} name={`optionDoubleConfirmationContent`} id={`optionDoubleConfirmationContent`} ref={`optionDoubleConfirmationContent`} /></div>
                  </Form.Item>
                ) : ''
              }
            </div>
          ) : ''
        }

        {
          getFieldValue("type") == 1 && getFieldValue("displayCardSelectedType") == 1 ? (
            <div>
              <Divider />
              <div className={styles.formTitle}><Icon style={{ transform: "rotate(90deg)" }} type='minus' />数据提交APIs</div>
              <Form.Item label="数据提交返回">
                {
                  getFieldDecorator("dataSubmitType",{initialValue:0,rules:[{required:true,message:"请输入"}]})(
                    <Radio.Group>
                      <Radio value={1}>是</Radio>
                      <Radio value={0}>否</Radio>
                    </Radio.Group>
                  )
                }
              </Form.Item>
              {
                getFieldValue("dataSubmitType") == 1 ? (
                  <div>
                    <Form.Item label="接口选择">
                      {
                        getFieldDecorator("submitApiId",{rules:[{required:true,message:"请选择"}]})(
                          <Select onChange={(value) => this.changeApiId(value,"submitInfo")}>
                            {
                              apiList.map(item => {
                                return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                              })
                            }
                          </Select>
                        )
                      }
                    </Form.Item>
                    <Form.Item label="请求参数赋值">
                    <ApiTableConfig 
                      title1="字段选择" 
                      title2="接口字段" 
                      options1={fieldsList} 
                      options2={submitInfo.requestList} 
                      list={resultFieldReqParam}
                      valueType1={'formFieldId'}
                      valueType2={'apiFieldId'}
                      changeOption={this.changeOption}
                      listType={'resultFieldReqParam'}
                      addContent={this.addContent}
                      removeContent={this.removeContent}
                      specialFlag={true}
                      apiList={apiList}
                      fieldsList={fieldsList}
                      changeFieldType={this.changeFieldType}
                    />
                  </Form.Item>
                  <Form.Item label="返回参数赋值">
                    <ApiTableConfig 
                      title1="接口字段" 
                      title2="表单字段" 
                      options1={submitInfo.responseList} 
                      options2={fieldsList} 
                      list={resultFieldResParam}
                      valueType2={'formFieldId'}
                      valueType1={'apiFieldId'}
                      changeOption={this.changeOption}
                      listType={'resultFieldResParam'}
                      addContent={this.addContent}
                      removeContent={this.removeContent}
                    />
                    
                  </Form.Item>
                  </div>
                ) : ''
              }
            </div>
          ) : ''
        }

        

        <Form.Item  label=" " colon={false} style={{marginBottom:0}}>
          {
            getFieldDecorator("resultShowType",{valuePropName: 'checked'})(
              <Checkbox>返回结果展示</Checkbox>
            )
          }
        </Form.Item>
        
        {
          //结果展示-1
          getFieldValue("resultShowType") ? (
            <Form.Item label="返回内容配置">
              <div style={{lineHeight:'24px'}}><Editor content={resultContent} name={`answerContent`} id={`answerContent`} ref={`answerContent`} /></div>
            </Form.Item>
          ) : ''
        }
        <Form.Item label=" " colon={false}>
          <Button type="primary" onClick={this.checkSave}>保存</Button>
        </Form.Item>

        <CardConfig onRef={ref => this.CardConfig = ref} setCardConfigData={this.setCardConfigData} leftFieldList={fieldsList} leftApiList={searchInfo.responseList} />
      </Form>
    )
  }
}

export default Form.create()(ApiNode)